#!/usr/bin/env python
# encoding: utf-8
'''
@author: zhaowenpeng
@contact: winston@peipeiyun.com
@software: garner
@file: update_order_agency.py
@time: 2020/8/9 2:26 下午
@desc:
'''


from peewee import *

user_mdb_w = {
    "host" : "192.168.10.111", #数值类型：字符串
    "port" : 3306, #数值类型：整型
    "username" : "root", #数值类型：字符串
    "pwd" : "root", #数值类型：字符串
    "db" : "users", #选择使用的database, 数值类型：字符串
}
from peewee import OperationalError,DateTimeField, MySQLDatabase,SqliteDatabase,BooleanField,CharField
from peewee import __exception_wrapper__
class RetryOperationalError(object):
    def execute_sql(self, sql, params=None, commit=True):
        try:
            cursor = super(RetryOperationalError, self).execute_sql(
                sql, params, commit)
        except OperationalError:
            if not self.is_closed():
                self.close()
            with __exception_wrapper__:
                cursor = self.cursor()
                cursor.execute(sql, params or ())
                if commit and not self.in_transaction():
                    self.commit()
        return cursor

class RetryMySQLDatabase(RetryOperationalError, MySQLDatabase):
    pass

database = RetryMySQLDatabase('users', **{'host': user_mdb_w.get('host'),
                                     'user':  user_mdb_w.get('username'),
                                     'passwd':  user_mdb_w.get('pwd'),
                                     'port':  user_mdb_w.get('port')})

class UnknownField(object):
    def __init__(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class UserAgencyRecommendationHistory(BaseModel):
    agency_yc_id = CharField(null=True)
    current_agency_yc_id = CharField(constraints=[SQL("DEFAULT ''")], null=True)
    datetime = DateTimeField(null=True)
    protect_time = DateTimeField(null=True)
    raise_status = IntegerField(constraints=[SQL("DEFAULT 0")], null=True)
    raise_time = DateTimeField(null=True)
    status = IntegerField(constraints=[SQL("DEFAULT 1")], null=True)
    update_time = DateTimeField(constraints=[SQL("DEFAULT CURRENT_TIMESTAMP")], null=True)
    user_yc_id = CharField(null=True)

    class Meta:
        table_name = 'user_agency_recommendation_history'
        primary_key = False



class UserAgencyRecommendation(BaseModel):
    agency_yc_id = CharField(null=True)
    current_agency_yc_id = CharField(null=True)
    datetime = DateTimeField(null=True)
    protect_time = DateTimeField(null=True)
    raise_status = IntegerField(constraints=[SQL("DEFAULT 0")], null=True)
    raise_time = DateTimeField(null=True)
    status = IntegerField(constraints=[SQL("DEFAULT 1")], null=True)
    update_time = DateTimeField(constraints=[SQL("DEFAULT CURRENT_TIMESTAMP")], null=True)
    user_yc_id = CharField(null=True)

    class Meta:
        table_name = 'user_agency_recommendation'
        indexes = (
            (('agency_yc_id', 'user_yc_id'), True),
            (('user_yc_id', 'current_agency_yc_id'), False),
        )
class UserOrderAgency(BaseModel):
    order_id = CharField(max_length=64,default='')
    yc_id = CharField(max_length=64,default='',)
    total = CharField(max_length=64,default='',)

    class Meta:
        table_name = 'user_order_agency'

import datetime

sql = "select order_id,yc_id from user_order where `STATUS`=2 and createtime>'2020-08-01 00:00:01"
cur = database.execute_sql(sql)
results = cur.fetchall()
for res in results:
    yc_id = res[1]
    out_trade_no = res[0]
    user_agency = UserAgencyRecommendation.get_or_none(UserAgencyRecommendation.user_yc_id == yc_id,
                                                       UserAgencyRecommendation.protect_time >= datetime.datetime.now())
    if user_agency:
        agency_yc_id=user_agency.current_agency_yc_id
    else:
        agency_yc_id = 'admin'
    user_order_agency = UserOrderAgency.get_or_none(UserOrderAgency.order_id==out_trade_no)
    if not user_order_agency:
        user_order_agency = UserOrderAgency()
        user_order_agency.order_id = out_trade_no
        user_order_agency.yc_id = agency_yc_id
        user_order_agency.save()